package com.wlz.ota.util;

import lombok.extern.slf4j.Slf4j;
import net.lingala.zip4j.ZipFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author wlz
 * @date 2022-11-03  10:26 上午
 */
@Slf4j
public class ZipCompressUtil {

    private static final int BUFFER_SIZE = 2 * 1024;


    public static File unZip4j(String zipFilePath, String unPackageOriginalPath, Charset charset) throws IOException {
        long time = System.currentTimeMillis();
        // 使用 zip4j 解压：首先指定 zip 文件
        ZipFile zipFile = new ZipFile(zipFilePath);
        // 指定编码集，主要是解决linux系统上中文乱码
        zipFile.setCharset(charset);
        // 指定要解压到的目录下，并解压
        zipFile.extractAll(unPackageOriginalPath);
        System.out.println(String.format("解压 【%s】 成功, 耗时:【%s】", zipFilePath, (System.currentTimeMillis() - time)));
        return new File(unPackageOriginalPath);
    }

    /**
     * 按文件夹压缩
     *
     * @param sourcePath 源文件夹路径
     * @param zipPath    压缩文件保存路径
     * @return
     */
    public static Boolean toZip(String sourcePath, String zipPath) {
        try {
            ZipOutputStream zos = null;
            FileOutputStream out = new FileOutputStream(new File(zipPath));
            try {
                zos = new ZipOutputStream(out);
                File sourceFile = new File(sourcePath);
                compress(sourceFile, zos, sourceFile.getName(), true);
            } catch (Exception e) {
                throw new RuntimeException("zip error from ZipCompressUtil", e);
            } finally {
                if (zos != null) {
                    try {
                        zos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("压缩文件异常", e);
            return false;
        }
    }

    /**
     * 递归压缩
     *
     * @param sourceFile       源文件
     * @param zos              zip输出流
     * @param name             压缩后的名称
     * @param KeepDirStructure 是否保留原来的目录结构(true:保留 false:不保留)
     * @throws Exception
     */
    private static void compress(File sourceFile, ZipOutputStream zos, String name, boolean KeepDirStructure) throws Exception {
        byte[] buf = new byte[BUFFER_SIZE];
        if (sourceFile.isFile()) {
            zos.putNextEntry(new ZipEntry(name));
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1) {
                zos.write(buf, 0, len);
            }
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if (listFiles == null || listFiles.length == 0) {
                if (KeepDirStructure) {
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    zos.closeEntry();
                }
            } else {
                for (File file : listFiles) {
                    if (KeepDirStructure) {
                        compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
                    } else {
                        compress(file, zos, file.getName(), KeepDirStructure);
                    }
                }
            }
        }
    }
}
